<!-- detail.vue -->
<template>
  <view class="task-detail">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="left" @click="goBack">
        <uni-icons type="left" size="20"></uni-icons>
        <text>返回</text>
      </view>
      <view class="title">任务详情</view>
      <view class="right" @click="saveTask">
        <text>保存</text>
      </view>
    </view>

    <!-- 任务内容 -->
    <view class="content">
      <!-- 基本信息 -->
      <view class="section">
        <view class="section-title">基本信息</view>
        <view class="form-item">
          <text class="label">标题</text>
          <input 
            type="text" 
            v-model="task.title"
            class="input" 
            placeholder="请输入任务标题"
          />
        </view>
        <view class="form-item">
          <text class="label">负责人</text>
          <picker 
            mode="selector" 
            :range="assignees" 
            range-key="name"
            @change="onAssigneeChange"
          >
            <view class="picker">
              {{ assignees.find(a => a.id === task.assignee)?.name || '请选择负责人' }}
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">优先级</text>
          <picker 
            mode="selector" 
            :range="priorities" 
            range-key="name"
            @change="onPriorityChange"
          >
            <view class="picker">{{ task.priority.name || '请选择优先级' }}</view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">状态</text>
          <picker 
            mode="selector" 
            :range="statuses" 
            range-key="name"
            @change="onStatusChange"
          >
            <view class="picker">{{ task.status.name || '请选择状态' }}</view>
          </picker>
        </view>
      </view>

      <!-- 任务描述 -->
      <view class="section">
        <view class="section-title">任务描述</view>
        <textarea 
          v-model="task.description"
          class="description-input"
          placeholder="请输入任务描述"
        />
      </view>

      <!-- 时间信息 -->
      <view class="section">
        <view class="section-title">时间信息</view>
        <view class="form-item">
          <text class="label">开始时间</text>
          <picker 
            mode="date" 
            :value="task.startTime"
            start="2020-01-01"
            end="2025-12-31"
            @change="onStartTimeChange"
          >
            <view class="picker">
              <text :class="{ placeholder: !task.startTime }">{{ task.startTime ? formatDate(task.startTime) : '请选择开始时间' }}</text>
              <uni-icons type="right" size="16" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">结束时间</text>
          <picker 
            mode="date" 
            :value="task.endTime"
            start="2020-01-01"
            end="2025-12-31"
            @change="onEndTimeChange"
          >
            <view class="picker">
              <text :class="{ placeholder: !task.endTime }">{{ task.endTime ? formatDate(task.endTime) : '请选择结束时间' }}</text>
              <uni-icons type="right" size="16" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">进度</text>
          <slider 
            :value="task.progress"
            @change="onProgressChange"
            show-value
            min="0"
            max="100"
            step="5"
          />
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import type { Task, Assignee, Priority, Status } from '../../types/task'
import { taskApi } from '../../services/task'

// 初始化一个完整的任务对象
const task = ref<Task>({
  id: '',
  title: '',
  description: '',
  assignee: '',
  priority: {
    id: '',
    name: '',
    color: ''
  },
  status: {
    id: '',
    name: '',
    color: ''
  },
  startTime: '',
  endTime: '',
  progress: 0
})

const assignees = ref<Assignee[]>([])
const priorities = ref<Priority[]>([])
const statuses = ref<Status[]>([])

// 获取任务详情
const fetchTaskDetail = async (taskId: string) => {
  try {
    const response = await taskApi.getTaskDetail(taskId)
    if (response?.task) {
      task.value = response.task
    }
  } catch (err) {
    uni.showToast({
      title: '获取任务详情失败',
      icon: 'error'
    })
  }
}

// 获取选项数据
const fetchOptions = async () => {
  try {
    const options = await taskApi.getOptions()
    assignees.value = options.assignees
    priorities.value = options.priorities
    statuses.value = options.statuses
  } catch (err) {
    uni.showToast({
      title: '获取选项数据失败',
      icon: 'error'
    })
  }
}

// 事件处理函数
const onAssigneeChange = (e: { detail: { value: number } }) => {
  const selectedAssignee = assignees.value[e.detail.value]
  if (selectedAssignee) {
    task.value.assignee = selectedAssignee.id
  }
}

const onPriorityChange = (e: { detail: { value: number } }) => {
  const selectedPriority = priorities.value[e.detail.value]
  if (selectedPriority) {
    task.value.priority = {
      id: selectedPriority.id,
      name: selectedPriority.name,
      color: selectedPriority.color
    }
  }
}

const onStatusChange = (e: { detail: { value: number } }) => {
  const selectedStatus = statuses.value[e.detail.value]
  if (selectedStatus) {
    task.value.status = {
      id: selectedStatus.id,
      name: selectedStatus.name,
      color: selectedStatus.color
    }
  }
}

const onStartTimeChange = (e: { detail: { value: string } }) => {
  task.value.startTime = e.detail.value
}

const onEndTimeChange = (e: { detail: { value: string } }) => {
  task.value.endTime = e.detail.value
}

const onProgressChange = (e: { detail: { value: number } }) => {
  task.value.progress = e.detail.value
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 保存任务
const saveTask = async () => {
  if (!task.value.id) return
  try {
    await taskApi.updateTask(task.value.id, task.value)
    uni.showToast({
      title: '保存成功',
      icon: 'success'
    })
    setTimeout(() => {
      goBack()
    }, 1500)
  } catch (err) {
    uni.showToast({
      title: '保存失败',
      icon: 'error'
    })
  }
}

// 删除任务
const deleteTask = async () => {
  if (!task.value.id) return
  try {
    await taskApi.deleteTask(task.value.id)
    uni.showToast({
      title: '删除成功',
      icon: 'success'
    })
    setTimeout(() => {
      goBack()
    }, 1500)
  } catch (err) {
    uni.showToast({
      title: '删除失败',
      icon: 'error'
    })
  }
}

// 页面加载时获取数据
onMounted(() => {
  const pages = getCurrentPages()
  const page = pages[pages.length - 1]
  // @ts-ignore
  const query = page.$page?.options as Record<string, string>
  if (query?.id) {
    Promise.all([fetchTaskDetail(query.id), fetchOptions()])
  }
})

const getStatusText = (status: Status) => {
  return status.name;
};

const getPriorityText = (priority: Priority) => {
  return priority.name;
};

const getPriorityIndex = (priority: Priority) => {
  return priorities.value.findIndex(option => option.id === priority.id);
};

const formatDate = (dateStr: string) => {
  if (!dateStr) return '';
  try {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  } catch (err) {
    return dateStr;
  }
}

const showActions = () => {
  uni.showActionSheet({
    itemList: ['删除任务'],
    success: (res) => {
      if (res.tapIndex === 0) {
        uni.showModal({
          title: '确认删除',
          content: '确定要删除该任务吗？',
          success: (res) => {
            if (res.confirm) {
              deleteTask();
            }
          }
        });
      }
    }
  });
};
</script>

<style lang="scss">
.task-detail {
  min-height: 100vh;
  background: #f5f7fa;
  
  .nav-bar {
    background: #4a6ee0;
    padding: 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #fff;
    
    .left {
      display: flex;
      align-items: center;
      font-size: 28rpx;
      
      .uni-icons {
        margin-right: 8rpx;
      }
    }
    
    .title {
      font-size: 32rpx;
      font-weight: bold;
    }

    .right {
      font-size: 28rpx;
      padding: 8rpx 24rpx;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 32rpx;
      
      &:active {
        opacity: 0.8;
      }
    }
  }
  
  .content {
    padding: 24rpx;
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    
    .section {
      background: #fff;
      border-radius: 12rpx;
      padding: 24rpx;
      margin-bottom: 24rpx;
      
      .section-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 16rpx;
      }
      
      .form-item {
        margin-bottom: 24rpx;
        
        .label {
          font-size: 28rpx;
          color: #666;
          margin-bottom: 8rpx;
          display: block;
        }
        
        .input {
          border: 2rpx solid #eee;
          border-radius: 8rpx;
          padding: 16rpx;
          font-size: 28rpx;
        }
        
        .picker {
          border: 2rpx solid #eee;
          border-radius: 8rpx;
          padding: 16rpx;
          font-size: 28rpx;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .placeholder {
            color: #999;
          }
        }
      }
    }
    
    .description {
      background: #fff;
      border-radius: 12rpx;
      padding: 24rpx;
      margin-bottom: 24rpx;
      
      .description-input {
        border: 2rpx solid #eee;
        border-radius: 8rpx;
        padding: 16rpx;
        font-size: 28rpx;
        width: 100%;
        height: 200rpx;
        margin-top: 16rpx;
      }
    }
    
    .progress {
      background: #fff;
      border-radius: 12rpx;
      padding: 24rpx;
      
      .timeline {
        margin-top: 24rpx;
        
        .timeline-item {
          position: relative;
          padding-left: 24rpx;
          margin-bottom: 24rpx;
          
          &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 12rpx;
            width: 12rpx;
            height: 12rpx;
            background: #4a6ee0;
            border-radius: 50%;
          }
          
          .time {
            font-size: 24rpx;
            color: #999;
            margin-bottom: 8rpx;
          }
          
          .content {
            font-size: 28rpx;
            
            .operator {
              color: #4a6ee0;
              margin-right: 8rpx;
            }
            
            .action {
              color: #333;
            }
          }
        }
      }
    }
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
}

.status-tag {
  padding: 4rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  
  &.status-todo {
    background: rgba(#909399, 0.1);
    color: #909399;
  }
  
  &.status-inProgress {
    background: rgba(#409eff, 0.1);
    color: #409eff;
  }
  
  &.status-completed {
    background: rgba(#67c23a, 0.1);
    color: #67c23a;
  }
}
</style> 